package funcktion;

import tools.BorrowGUI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BookSearch extends JFrame {
    private JTextField searchField;
    private JComboBox<String> sortComboBox;
    private JTextArea resultTextArea;

    public BookSearch(int userId) {
        setTitle("图书查询");
        setSize(1100, 800);
        setLocationRelativeTo(null);

        // 创建查询面板
        JPanel searchPanel = new JPanel();
        searchPanel.setLayout(new FlowLayout());

        JLabel searchLabel = new JLabel("图书编号或名称：");
        searchField = new JTextField(20);


        searchPanel.add(searchLabel);
        searchPanel.add(searchField);
        // 创建结果显示面板
        resultTextArea = new JTextArea();
        resultTextArea.setEditable(false);

        // 创建排序等操作面板
        JPanel sortPanel = new JPanel();
        sortPanel.setLayout(new FlowLayout());

        JLabel sortLabel = new JLabel("排序方式：");
        sortComboBox = new JComboBox<>(new String[]{"默认", "编号", "名称"});
        JButton sortButton = new JButton("查询");
        JButton borrowButton = new JButton("借书");


        sortPanel.add(sortLabel);
        sortPanel.add(sortComboBox);
        sortPanel.add(sortButton);
        sortPanel.add(borrowButton);

        // 添加组件到主面板
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(searchPanel, BorderLayout.NORTH);
        contentPane.add(new JScrollPane(resultTextArea), BorderLayout.CENTER);
        contentPane.add(sortPanel, BorderLayout.SOUTH);


        //初始查询结果
        String keyword = searchField.getText();
        String sortField = (String) sortComboBox.getSelectedItem();
        searchBooks(keyword, sortField);

        // 注册排序按钮事件监听器
        sortButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String keyword = searchField.getText();
                String sortField = (String) sortComboBox.getSelectedItem();
//                System.out.println(keyword);
//                System.out.println(sortField);
                searchBooks(keyword, sortField);
                // 使用排序后的图书列表进行后续操作
            }
        });


        borrowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                BorrowGUI GUI = new BorrowGUI(userId);
                GUI.setVisible(true);
                //借书
            }
        });

    }

    private void searchBooks(String keyword, String sortField) {
        List<Book> searchResult = new ArrayList<>();

        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/library";
        String username = "root";
        String password = "lang520520";

        try {
            // 连接数据库
            Connection connection = DriverManager.getConnection(url, username, password);

            // 构造SQL查询语句
            String sql = "SELECT * FROM Book WHERE bookId LIKE ? OR bookName LIKE ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, "%" + keyword + "%");
            statement.setString(2, "%" + keyword + "%");

            // 执行查询
            ResultSet resultSet = statement.executeQuery();

            // 处理查询结果
            while (resultSet.next()) {
                String bookId = resultSet.getString("bookId");
                String bookName = resultSet.getString("bookName");
                double price = resultSet.getDouble("price");
                int totalCopies = resultSet.getInt("totalCopies");
                int availableCopies = resultSet.getInt("availableCopies");
                String status = resultSet.getString("status");

                Book book = new Book(bookId, bookName, price, totalCopies, availableCopies, status);
                searchResult.add(book);
            }

            // 关闭连接和语句
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }    // 根据排序字段排序查询结果
        sortBooks(searchResult, sortField);

        // 显示查询结果
        displayBooks(searchResult);
    }

    private void sortBooks(List<Book> books, String sortField) {
        switch (sortField) {
            case "编号":
                Collections.sort(books, new BookIdComparator());
                break;
            case "名称":
                Collections.sort(books, new BookNameComparator());
                break;
            default:
                // 默认按数据库返回的顺序，无需排序
                break;
        }
    }

    private void displayBooks(List<Book> books) {
        StringBuilder sb = new StringBuilder();
        for (Book book : books) {
            sb.append("图书编号: ").append(book.getBookId()).append("\n");
            sb.append("图书名称: ").append(book.getBookName()).append("\n");
            sb.append("价格: ").append(book.getPrice()).append("\n");
            sb.append("总库存: ").append(book.getTotalCopies()).append("\n");
            sb.append("可借库存: ").append(book.getAvailableCopies()).append("\n");
            sb.append("状态: ").append(book.getStatus()).append("\n");
            sb.append("--------------------\n");
        }
        resultTextArea.setText(sb.toString());
    }

    private class Book {
        private String bookId;
        private String bookName;
        private double price;
        private int totalCopies;
        private int availableCopies;
        private String status;

        public Book(String bookId, String bookName, double price, int totalCopies, int availableCopies, String status) {
            this.bookId = bookId;
            this.bookName = bookName;
            this.price = price;
            this.totalCopies = totalCopies;
            this.availableCopies = availableCopies;
            this.status = status;
        }

        public String getBookId() {
            return bookId;
        }

        public String getBookName() {
            return bookName;
        }

        public double getPrice() {
            return price;
        }

        public int getTotalCopies() {
            return totalCopies;
        }

        public int getAvailableCopies() {
            return availableCopies;
        }

        public String getStatus() {
            return status;
        }
    }

    private class BookIdComparator implements Comparator<Book> {
        @Override
        public int compare(Book book1, Book book2) {
            return book1.getBookId().compareTo(book2.getBookId());
        }
    }

    private class BookNameComparator implements Comparator<Book> {
        @Override
        public int compare(Book book1, Book book2) {
            return book1.getBookName().compareTo(book2.getBookName());
        }
    }
}